from flask import Flask, url_for, redirect, request, render_template
import time, os
from config import MainConfig
from datetime import timedelta, date
import redis
from utils.spider_name import spiders_name

pool = redis.ConnectionPool(host='120.77.159.174', port=6379, db=15)
r = redis.Redis(connection_pool=pool)

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=2)
app.config.from_object(MainConfig)

users = [] # 这里存放所有信息


@app.route('/user/')
def index():
    print(url_for('index', id=10, name='Ramsey', age=24))
    return 'Test'

@app.route('/get/',methods=['GET', 'POST'])
def demo01():
    if request.method == 'GET':
        return render_template('form.html')

    if request.method == 'POST':
        name = request.form.get('name')
        age = request.form.get('age')
        print("name: %s \nage: %s " % (name, age))
    return '已经获取数据'

@app.route('/check/')
def demo03():
    today = str(date.today())
    users = []
    everyday = []
    count = 1
    everydays = sorted([int(time.mktime(time.strptime(i.decode(), "%Y-%m-%d"))) for i in r.keys()[:11]], reverse = True)
    hehe = r.hgetall(today)
    # 存放每天的日期
    for each_day in everydays[:8]:
        everyday.append(time.strftime("%Y-%m-%d", time.localtime(each_day)))
    for each in hehe.items():
        users.append({
            "title": str(count) + '.' + each[0].decode(),
            "number": each[1].decode(),
            "url": spiders_name.get(each[0].decode(), '123')
        })
        count += 1
    return render_template('show_message.html', says=users, data=today, date01=everyday)


@app.route('/check/<which_date>/', methods=['GET','POST'])
def demo02(which_date=''):
    if request.method == 'GET':
        today = str(date.today())
        users = []
        everyday = []
        count = 1
        everydays = sorted([int(time.mktime(time.strptime(i.decode(), "%Y-%m-%d"))) for i in r.keys()[:11]], reverse = True)
        hehe = r.hgetall(which_date)
        # 存放每天的日期
        for each_day in everydays[:8]:
            everyday.append(time.strftime("%Y-%m-%d",time.localtime(each_day)))

        for each in hehe.items():
            users.append({
                          "title" : str(count) + '.' + each[0].decode(),
                          "number" : each[1].decode(),
                          "url" : spiders_name.get(each[0].decode(), '123')
                          })
            count += 1
        return render_template('show_message.html', says = users, data = which_date, date01 = everyday)

if __name__ == '__main__':
    app.run(host='192.168.0.140',port=8888)
